package com.diorsunion.hedge.io.netty;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * Created by dingshan.yyj on 2016/5/26.
 */
public class NettyChannelInitializer extends ChannelInitializer<SocketChannel> {

    final KryoPool kryoPool;//这里为什么是kryoPool而不是decoder,注意，因为KryoDecoder是不可共享的，所以每次都得实例化一个
    final ChannelHandlerAdapter channelHandlerAdapter;


    final int readerIdleTimeSeconds;
    final int writerIdleTimeSeconds;
    final int allIdleTimeSeconds;

    public NettyChannelInitializer(KryoPool kryoPool, ChannelHandlerAdapter channelHandlerAdapter, int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
        this.kryoPool = kryoPool;
        this.channelHandlerAdapter = channelHandlerAdapter;
        this.readerIdleTimeSeconds = readerIdleTimeSeconds;
        this.writerIdleTimeSeconds = writerIdleTimeSeconds;
        this.allIdleTimeSeconds = allIdleTimeSeconds;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline channelPipeline = socketChannel.pipeline();
//            channelPipeline.addLast(new IdleStateHandler(20, 10, 0));
//            channelPipeline.addLast("encoder", new ObjectEncoder());
        channelPipeline.addFirst(
                new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds),
                new KryoDecoder(kryoPool),
                channelHandlerAdapter,
                new KryoEncoder(kryoPool));
//        channelPipeline.addLast();
//        channelPipeline.addLast();
//            channelPipeline.addLast("decoder", new ObjectDecoder(1024 * 1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));

//        channelPipeline.addLast();
    }
}
